package com.koron.css2.meterService.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.baseConfig.mapper.BaseReceiptAccessoryMapper;
import com.koron.css2.meterService.bean.MsVerifyBean;
import com.koron.css2.meterService.mapper.MsVerifyMapper;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.util.Constant;
import com.koron.util.Tools;
import com.koron.util.ValidationKey;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 校表添加
 * @author 周利斌
 *
 */
public class MsVeriAdd implements ServerInterface{
	
	private static Logger log = LogManager.getLogger(MsVeriAdd.class);

	@Override
    @ValidationKey(clazz = MsVerifyBean.class,method = "insert")
	public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
		
		MessageBean<Map> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "添加成功", Map.class);
		try {
			MsVerifyBean bean = JsonUtils.objectToPojo(req.getData(), MsVerifyBean.class);
			MsVerifyMapper mapper = factory.getMapper(MsVerifyMapper.class);
			String billNo = mapper.selectProcessNotEnd(bean.getMeterNo(), bean.getId());
			if(billNo!=null) {
				return MessageBean.create(Constant.MESSAGE_INT_FAIL, "水表编号"+bean.getMeterNo()+"存在未结束的工作流,单据编号:"+billNo, void.class);
			}
			bean.setBillDate(new Date());
			bean.setBillNo(Tools.getBillNo(factory, "ms_verify"));
			bean.setCreateInfo(userInfo);
			int iCount = mapper.addMsVerify(bean);
			if(iCount < 1) {
				info.setCode(Constant.MESSAGE_INT_FAIL);
				info.setDescription("添加失败");
			}
			Map<String, String> data = new HashMap<String, String>();
			data.put("id", bean.getId());
			info.setData(data);
			BaseReceiptAccessoryMapper accessoryMapper = factory.getMapper(BaseReceiptAccessoryMapper.class);
			if(!StringUtils.isBlank(bean.getTempId()))		//修改附件ID
				accessoryMapper.updateAccessoryReceiptId(bean.getId(), bean.getTempId());
		} catch (Exception e) {
			info.setCode(Constant.MESSAGE_INT_FAIL);
			info.setDescription("添加失败");
			log.error(e.getMessage(), e);
		}
		return info;
	}

}
